import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/message")
public class MessageWall extends HttpServlet {
    //这个对象多个方法都要使用
    private ObjectMapper objectMapper = new ObjectMapper();

    //让页面获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //显式声明响应数据格式
        resp.setContentType("application/json; charset=utf8");
        //从数据库中拿数据，转成json字符串，返回给页面
        try {
            resp.getWriter().write(objectMapper.writeValueAsString(load()));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取body中的数据并解析
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //将message保存到内存中
        try {
            save(message);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //表示成功提交数据
        resp.setStatus(200);//可有可无
        System.out.println("提交数据成功: from=" + message.getFrom()
        + ", to=" + message.getTo() + ", message=" + message.getMessage());
    }
//___________________数据库_________________________
    //提交数据
    private List<Message> load() throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/messagewall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1111");

        //2.建立连接
        Connection connection = (Connection) dataSource.getConnection();

        //3.构造sql
        String sql = "select * from message";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4.构造sql
        ResultSet resultSet = statement.executeQuery();

        //5.遍历结果集合
        List<Message> messageList = new ArrayList<>();
        while(resultSet.next()) {
            Message message = new Message();
            message.setFrom(resultSet.getString("from"));
            message.setTo(resultSet.getString("to"));
            message.setMessage(resultSet.getString("message"));
            messageList.add(message);
        }
        statement.close();
        connection.close();
        return messageList;
    }

    //保存数据到数据库
    private void save(Message message) throws SQLException {
        //1.床架数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/messagewall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1111");

        //2.建立连接
        Connection connection = (Connection) dataSource.getConnection();

        //3.构造SQL
        String sql = "insert into message value(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, message.getFrom());
        statement.setString(2,message.getTo());
        statement.setString(3, message.getMessage());

        //4.执行sql
        int ret = statement.executeUpdate();
        System.out.println("ret = " + ret);

        //5.关闭连接
        statement.close();
        connection.close();
    }
}
